from django.shortcuts import render

from .models import Book, TimeManage

# Create your views here.
from django.http import HttpResponse, HttpResponseRedirect
# import datetime
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.urls import reverse
from .forms import BookForm

@login_required
def index(request):
	"""显示借还界面"""
	try:
		# x = 0
		books = Book.objects.order_by('id')
		br_records = TimeManage.objects.order_by('id')
		# for book in books:
			# if book.state:
			# 	x += 1
		context = {'books': books, 'br_records': br_records}
	except:
		pass
	else:		
		return render(request, 'libraries/index.html', context)

@login_required
def books(request):
	"""未借出书本的展示"""
	x = 0
	books = Book.objects.order_by('id')
	for book in books:
		if book.state == 0:
			x += 1
	context = {'books': books,'x': x}
	return render(request, 'libraries/books.html', context)

@login_required
def books_returns(request):
	"""已借出书本的展示"""
	x = 0
	books = Book.objects.order_by('id')
	for book in books:
		if book.state == 1:
			x += 1	
	context = {'books': books,'x': x}
	return render(request, 'libraries/books_returns.html', context)

@login_required
def borrows(request):
	"""书籍+1"""
	pks = request.POST.getlist('pk', [])
	for pk in pks:
		loan = Book.objects.get(id=pk)
		loan.times += 1
		loan.state = True
		loan.owner = request.user
		loan.save()
		TimeManage.objects.create(name=loan, state=loan.state)
	return HttpResponseRedirect('books')

@login_required
def returns(request):
	"""书籍归还"""
	pks = request.POST.getlist('pk', [])
	if pks != []:
		for pk in pks:
			book = Book.objects.get(id=pk)
			book.state = False
			book.owner = None
			book.save()
			TimeManage.objects.create(name=book, state=book.state)
		return HttpResponse('您的书籍已归还！')
	else:
		return HttpResponse('未选择任何书籍！')

@login_required
def new_books(request):
	"""后台书籍添加"""
	books = Book.objects.order_by('id')
	if request.method != 'POST':
		# 未提交数据： 创建一个新表单
		form = BookForm()
	else:
		# POST提交的数据，对数据进行处理
		form = BookForm(request.POST)
		if form.is_valid():
			form.save()
			return HttpResponseRedirect(reverse('libraries:new_books'))

	context = {'form': form, 'books': books}
	return render(request, 'libraries/new_books.html', context)

@login_required
def book_detail(request, pk):
    """显示单本书籍详细新"""
    book = Book.objects.get(id=pk)

    return render(request, 'libraries/book_detail.html', {'book':book})